package com.yexx.starter.security.sms;

import com.yexx.starter.security.basic.SecurityUserDetailsService;
import com.yexx.starter.security.basic.constant.SecurityConstants;
import com.yexx.utils.CacheUtil;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * Description: 短信验证码认证 adapter
 *
 * @author: zuomin (myleszelic@outlook.com)
 * @date: 2020/11/03 14:16
 */
public class SmsCodeAuthenticationSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {

    private CacheUtil cacheUtil;

    private SecurityUserDetailsService userDetailsService;

    private String superSmsCode;
    private Boolean singleSignOn = false;

    public SmsCodeAuthenticationSecurityConfig(CacheUtil cacheUtil, SecurityUserDetailsService userDetailsService, String superSmsCode, Boolean singleSignOn) {
        this.cacheUtil = cacheUtil;
        this.userDetailsService = userDetailsService;
        this.superSmsCode = superSmsCode;
        this.singleSignOn = singleSignOn;
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        //自定义SmsCodeAuthenticationFilter过滤器
        SmsCodeAuthenticationFilter smsCodeAuthenticationFilter = new SmsCodeAuthenticationFilter(SecurityConstants.PATH.LOGIN_PHONE_NUM_SMS, SecurityConstants.PATH.LOGIN_ERROR, singleSignOn);
        smsCodeAuthenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
        smsCodeAuthenticationFilter.setCacheUtil(cacheUtil);
        smsCodeAuthenticationFilter.setUserDetailsService(userDetailsService);

        //设置自定义SmsCodeAuthenticationProvider的认证器userDetailsService
        SmsCodeAuthenticationProvider smsCodeAuthenticationProvider = new SmsCodeAuthenticationProvider();
        smsCodeAuthenticationProvider.setSecurityUserService(userDetailsService);
        smsCodeAuthenticationProvider.setCacheUtil(cacheUtil);
        smsCodeAuthenticationProvider.setSuperSmsCode(superSmsCode);

        //在UsernamePasswordAuthenticationFilter过滤前执行
        http.authenticationProvider(smsCodeAuthenticationProvider).addFilterAfter(smsCodeAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
    }
}
